<!DOCTYPE html>
<html lang="zh-CN,en,zh-TW,default">
  <head hexo-theme='https://github.com/volantis-x/hexo-theme-volantis/tree/4.2.0'>
  <meta charset="utf-8">
  <!-- SEO相关 -->
  
    
  
  <!-- 渲染优化 -->
  <meta http-equiv='x-dns-prefetch-control' content='on' />
  <link rel='dns-prefetch' href='https://cdn.jsdelivr.net'>
  <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <!-- 页面元数据 -->
  
  <title>Spring AOP 源码解析 - Yayako&#39;s Blog</title>
  
    <meta name="keywords" content="源码,Spring">
  

  
    <meta name="description" content="jdk动态代理与cglib代理的简单区别？Spring实现aop的流程？">
  

  <!-- feed -->
  

  <!-- import meta -->
  

  <!-- link -->
  
    <link rel="shortcut icon" type='image/x-icon' href="https://halo-yayako.oss-cn-hangzhou.aliyuncs.com/icons8-lamb-96_1600147384617.png">
  

  <!-- import link -->
  

  
    
<link rel="stylesheet" href="/css/first.css">

  

  
  <link rel="stylesheet" href="/css/style.css" media="print" onload="this.media='all';this.onload=null">
  <noscript><link rel="stylesheet" href="/css/style.css"></noscript>
  

  <script id="loadcss"></script>

  

<script>if (/*@cc_on!@*/false || (!!window.MSInputMethodContext && !!document.documentMode)) document.write('\x3Cscript id="_iealwn_js" data-outver="11" src="https://support.dmeng.net/ie-alert-warning/latest.js">\x3C/script>'); </script>

</head>

  <body>
    

<header id="l_header" class="l_header always shadow blur "  >
  <div class='container'>
  <div id='wrapper'>
    <div class='nav-sub'>
      <p class="title"></p>
      <ul class='switcher nav-list-h m-phone' id="pjax-header-nav-list">
        <li><a id="s-comment" class="fas fa-comments fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
          <li><a id="s-toc" class="s-toc fas fa-list fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
      </ul>
    </div>
		<div class="nav-main">
      
        
        <a class="title flat-box" target="_self" href='/'>
          
            <img no-lazy class='logo' src='https://yayako-blog.oss-cn-hangzhou.aliyuncs.com/settings/icons8-doughnut-100.png'/>
          
          
          
        </a>
      

			<div class='menu navigation'>
				<ul class='nav-list-h m-pc'>
          
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/
                  
                  
                  
                    id="categoriesJava"
                  >
                  Java
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/%E5%9F%BA%E7%A1%80/
                  
                  
                  
                    id="categoriesJavaE59FBAE7A180"
                  >
                  基础
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/JVM/
                  
                  
                  
                    id="categoriesJavaJVM"
                  >
                  JVM
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/J.U.C/
                  
                  
                  
                    id="categoriesJavaJUC"
                  >
                  J.U.C
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Golang/
                  
                  
                  
                    id="categoriesGolang"
                  >
                  Golang
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Golang/%E5%9F%BA%E7%A1%80
                  
                  
                  
                    id="categoriesGolangE59FBAE7A180"
                  >
                  基础
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E6%A1%86%E6%9E%B6/
                  
                  
                  
                    id="categoriesE6A186E69EB6"
                  >
                  框架
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E6%A1%86%E6%9E%B6/SSM/
                  
                  
                  
                    id="categoriesE6A186E69EB6SSM"
                  >
                  SSM
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/
                  
                  
                  
                    id="categoriesE4B8ADE997B4E4BBB6"
                  >
                  中间件
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/Redis/
                  
                  
                  
                    id="categoriesE4B8ADE997B4E4BBB6Redis"
                  >
                  Redis
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/MySQL/
                  
                  
                  
                    id="categoriesMySQL"
                  >
                  MySQL
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/MySQL/%E5%9F%BA%E7%A1%80/
                  
                  
                  
                    id="categoriesMySQLE59FBAE7A180"
                  >
                  基础
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/MySQL/InnoDB/
                  
                  
                  
                    id="categoriesMySQLInnoDB"
                  >
                  InnoDB
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E7%AE%97%E6%B3%95/
                  
                  
                  
                    id="categoriesE7AE97E6B395"
                  >
                  算法
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E7%AE%97%E6%B3%95/LeetCode/
                  
                  
                  
                    id="categoriesE7AE97E6B395LeetCode"
                  >
                  LeetCode
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E7%AE%97%E6%B3%95/%E5%89%91%E6%8C%87offer/
                  
                  
                  
                    id="categoriesE7AE97E6B395E58991E68C87offer"
                  >
                  剑指offer
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/
                  
                  
                  
                    id="categoriesE5B7A5E585B7"
                  >
                  工具
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/Linux/
                  
                  
                  
                    id="categoriesE5B7A5E585B7Linux"
                  >
                  Linux
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/Nginx/
                  
                  
                  
                    id="categoriesE5B7A5E585B7Nginx"
                  >
                  Nginx
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/Docker/
                  
                  
                  
                    id="categoriesE5B7A5E585B7Docker"
                  >
                  Docker
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%85%B6%E4%BB%96/
                  
                  
                  
                    id="categoriesE585B6E4BB96"
                  >
                  其他
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%85%B6%E4%BB%96/%E9%9D%A2%E7%BB%8F/
                  
                  
                  
                    id="categoriesE585B6E4BB96E99DA2E7BB8F"
                  >
                  面经
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
				</ul>
			</div>

      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <i class="icon fas fa-search fa-fw"></i>
          <input type="text" class="input u-search-input" placeholder="Search..." />
        </form>
      </div>

			<ul class='switcher nav-list-h m-phone'>
				
					<li><a class="s-search fas fa-search fa-fw" target="_self" href='javascript:void(0)'></a></li>
				
				<li>
          <a class="s-menu fas fa-bars fa-fw" target="_self" href='javascript:void(0)'></a>
          <ul class="menu-phone list-v navigation white-box">
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/
                  
                  
                  
                    id="categoriesJava"
                  >
                  Java
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/%E5%9F%BA%E7%A1%80/
                  
                  
                  
                    id="categoriesJavaE59FBAE7A180"
                  >
                  基础
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/JVM/
                  
                  
                  
                    id="categoriesJavaJVM"
                  >
                  JVM
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Java/J.U.C/
                  
                  
                  
                    id="categoriesJavaJUC"
                  >
                  J.U.C
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Golang/
                  
                  
                  
                    id="categoriesGolang"
                  >
                  Golang
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/Golang/%E5%9F%BA%E7%A1%80
                  
                  
                  
                    id="categoriesGolangE59FBAE7A180"
                  >
                  基础
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E6%A1%86%E6%9E%B6/
                  
                  
                  
                    id="categoriesE6A186E69EB6"
                  >
                  框架
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E6%A1%86%E6%9E%B6/SSM/
                  
                  
                  
                    id="categoriesE6A186E69EB6SSM"
                  >
                  SSM
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/
                  
                  
                  
                    id="categoriesE4B8ADE997B4E4BBB6"
                  >
                  中间件
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/Redis/
                  
                  
                  
                    id="categoriesE4B8ADE997B4E4BBB6Redis"
                  >
                  Redis
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/MySQL/
                  
                  
                  
                    id="categoriesMySQL"
                  >
                  MySQL
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/MySQL/%E5%9F%BA%E7%A1%80/
                  
                  
                  
                    id="categoriesMySQLE59FBAE7A180"
                  >
                  基础
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/MySQL/InnoDB/
                  
                  
                  
                    id="categoriesMySQLInnoDB"
                  >
                  InnoDB
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E7%AE%97%E6%B3%95/
                  
                  
                  
                    id="categoriesE7AE97E6B395"
                  >
                  算法
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E7%AE%97%E6%B3%95/LeetCode/
                  
                  
                  
                    id="categoriesE7AE97E6B395LeetCode"
                  >
                  LeetCode
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E7%AE%97%E6%B3%95/%E5%89%91%E6%8C%87offer/
                  
                  
                  
                    id="categoriesE7AE97E6B395E58991E68C87offer"
                  >
                  剑指offer
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/
                  
                  
                  
                    id="categoriesE5B7A5E585B7"
                  >
                  工具
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/Linux/
                  
                  
                  
                    id="categoriesE5B7A5E585B7Linux"
                  >
                  Linux
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/Nginx/
                  
                  
                  
                    id="categoriesE5B7A5E585B7Nginx"
                  >
                  Nginx
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%B7%A5%E5%85%B7/Docker/
                  
                  
                  
                    id="categoriesE5B7A5E585B7Docker"
                  >
                  Docker
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%85%B6%E4%BB%96/
                  
                  
                  
                    id="categoriesE585B6E4BB96"
                  >
                  其他
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/%E5%85%B6%E4%BB%96/%E9%9D%A2%E7%BB%8F/
                  
                  
                  
                    id="categoriesE585B6E4BB96E99DA2E7BB8F"
                  >
                  面经
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
          </ul>
        </li>
			</ul>
		</div>
	</div>
  </div>
</header>

    <div id="l_body">
      <div id="l_cover">
  
    
        <div id="half" class='cover-wrapper post search' style="display: ;">
          
            <div id='cover-backstretch'></div>
          
          <div class='cover-body'>
  <div class='top'>
    
    
      <p class="title">Yayako's Blog</p>
    
    
      <p class="subtitle">「Shooting for the stars when I couldn't make a killing.」</p>
    
  </div>
  <div class='bottom'>
    
      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <input type="text" class="input u-search-input" placeholder="Have a nice day!" />
          <i class="icon fas fa-search fa-fw"></i>
        </form>
      </div>
    
    <div class='menu navigation'>
      <div class='list-h'>
        
          
            <a href="/"
              
              
              id="home">
              <i class='fas fa-home fa-fw'></i><p>首页</p>
            </a>
          
            <a href="/categories/"
              
              
              id="categories">
              <i class='fas fa-folder-open fa-fw'></i><p>分类</p>
            </a>
          
            <a href="/archives/"
              
              
              id="archives">
              <i class='fas fa-archive fa-fw'></i><p>归档</p>
            </a>
          
            <a href="/tags/"
              
              
              id="tags">
              <i class='fas fa-tags fa-fw'></i><p>标签</p>
            </a>
          
            <a href="/friends/"
              
              
              id="friends">
              <i class='fas fa-link fa-fw'></i><p>友链</p>
            </a>
          
            <a href="/about/"
              
              
              id="about">
              <i class='fas fa-user fa-fw'></i><p>关于</p>
            </a>
          
        
      </div>
    </div>
  </div>
</div>

          <div id="scroll-down" style="display: none;"><i class="fa fa-chevron-down scroll-down-effects"></i></div>
        </div>
    
  
  </div>

      <div id="safearea">
        <div class="body-wrapper" id="pjax-container">
          

<div class='l_main'>
  <article class="article post white-box reveal md shadow article-type-post" id="post" itemscope itemprop="blogPost">
  


  
  <div class="article-meta" id="top">
    
    
    
      <h1 class="title">
        Spring AOP 源码解析
      </h1>
      <div class='new-meta-box'>
        
          
            
<div class='new-meta-item author'>
  <a class='author' href="/about" rel="nofollow">
    <img no-lazy src="https://yayako-blog.oss-cn-hangzhou.aliyuncs.com/settings/icons8-cat-100%20%282%29.png">
    <p>yayako</p>
  </a>
</div>

          
        
          
            <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i>
    <p>发布于：2020年6月7日</p>
  </a>
</div>

          
        
          
            
  <div class="new-meta-item browse leancloud">
    <a class='notlink'>
      
      <div id="lc-pv" data-title="Spring AOP 源码解析" data-path="/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/">
        <i class="fas fa-eye fa-fw" aria-hidden="true"></i>
        <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
        次浏览
      </div>
    </a>
  </div>


          
        
          
            
<div class="new-meta-item comments-count">
  
  <a href="/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/#comments">
    <i class="fas fa-comment-dots fa-fw"></i>
    <span class="valine-comment-count" data-xid="/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/">0</span>
    <span class="leancloud-comments-count">&nbsp;条评论</span>
  </a>
</div>


          
        
      </div>
    
  </div>


  
  
  <h1 id="jdk动态代理与cglib代理的区别"><a href="#jdk动态代理与cglib代理的区别" class="headerlink" title="jdk动态代理与cglib代理的区别"></a>jdk动态代理与cglib代理的区别</h1><p>在spring aop的实现中，</p>
<ul>
<li>如果目标对象实现了接口，默认情况下会采用jdk动态代理实现aop，也可以强制使用cglib实现aop（添加库，配置proxy-target-class）；</li>
<li>如果目标对象实现了接口，可以强制使用cglib实现aop；</li>
<li>如果目标对象没有实现接口，必须采用cglib代理库，spring会自动在jdk动态代理和cglib之间转换。</li>
</ul>
<h2 id="jdk动态代理"><a href="#jdk动态代理" class="headerlink" title="jdk动态代理"></a>jdk动态代理</h2><p>代理对象必须是某个接口的实现，它是通过在运行期间创建一个接口的实现类来完成对目标对象的代理。</p>
<h2 id="cglib代理"><a href="#cglib代理" class="headerlink" title="cglib代理"></a>cglib代理</h2><p>实现原理类似jdk动态代理，只是它在运行期间生成的代理对象是针对目标类扩展的子类。性能强于jdk动态代理。且因为是继承，该类或方法最好不要声明成final。</p>
<h2 id="静态代理"><a href="#静态代理" class="headerlink" title="静态代理"></a>静态代理</h2><p>在虚拟机启动时通过改变目标对象对字节码的方式来完成对目标对象的增强，与动态代理相比具有更高的效率，因为后者在动态代理调用的过程中还需要一个动态创建代理类并代理目标对象的步骤，而静态代理则是在启动时便完成了字节码增强。</p>
<h1 id="代理源码解析"><a href="#代理源码解析" class="headerlink" title="代理源码解析"></a>代理源码解析</h1><p>在spring bean的加载流程中，还记得有这样一步，在创建bean时，会先进行实例化前置处理，也即postProccessAfterIntialization函数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">    <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"><span class="comment">// 省略......</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// Give BeanPostProcessors a chance to return a proxy instead of the target bean</span></span><br><span class="line">        <span class="comment">// instance.</span></span><br><span class="line">        <span class="comment">// 实例化前置处理（AOP判断）</span></span><br><span class="line">        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);</span><br><span class="line">        <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> bean;</span><br><span class="line">        &#125;</span><br><span class="line"><span class="comment">// 省略......</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在每一个bena创建之前进行拦截</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">resolveBeforeInstantiation</span><span class="params">(String beanName, RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">    Object bean = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) &#123;</span><br><span class="line">        <span class="comment">// Make sure bean class is actually resolved at this point.</span></span><br><span class="line">        <span class="keyword">if</span> (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">            Class&lt;?&gt; targetType = determineTargetType(beanName, mbd);</span><br><span class="line">            <span class="keyword">if</span> (targetType != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// 实例化前的后置处理器</span></span><br><span class="line">                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);</span><br><span class="line">                <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="comment">// 实例化前的后置处理器</span></span><br><span class="line">                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        mbd.beforeInstantiationResolved = (bean != <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> bean;</span><br><span class="line">&#125;</span><br><span class="line">    </span><br><span class="line"><span class="comment">// 前置</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">applyBeanPostProcessorsBeforeInstantiation</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (BeanPostProcessor bp : getBeanPostProcessors()) &#123;</span><br><span class="line">        <span class="comment">// 如果是aop的话，spring会默认配置该类型的BeanPostProcessor，这种后置处理器会在bean创建前全部拦截</span></span><br><span class="line">        <span class="keyword">if</span> (bp <span class="keyword">instanceof</span> InstantiationAwareBeanPostProcessor) &#123;</span><br><span class="line">            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;</span><br><span class="line">            <span class="comment">// 实例化前置处理</span></span><br><span class="line">            Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);</span><br><span class="line">            <span class="keyword">if</span> (result != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> result;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 后置</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">applyBeanPostProcessorsAfterInitialization</span><span class="params">(Object existingBean, String beanName)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"></span><br><span class="line">    Object result = existingBean;</span><br><span class="line">    <span class="keyword">for</span> (BeanPostProcessor processor : getBeanPostProcessors()) &#123;</span><br><span class="line">        <span class="comment">// 调用后置处理器的后置方法</span></span><br><span class="line">        Object current = processor.postProcessAfterInitialization(result, beanName);</span><br><span class="line">        <span class="keyword">if</span> (current == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">        result = current;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>实例化后置处理postProcessAfterInitialization</p>
<p>bean的增强就是在这个后置处理中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(<span class="meta">@Nullable</span> Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="comment">// 根据给定的bean的class和name构建出一个key</span></span><br><span class="line">        Object cacheKey = getCacheKey(bean.getClass(), beanName);</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.earlyProxyReferences.remove(cacheKey) != bean) &#123;</span><br><span class="line">             <span class="comment">// 如果适合被代理，则需要封装指定bean</span></span><br><span class="line">            <span class="keyword">return</span> wrapIfNecessary(bean, beanName, cacheKey);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> bean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>wrapIfNecessary(Object bean, String beanName, Object cacheKey)</p>
<ol>
<li>获取增强方法或者增强器</li>
<li>根据获取的增强进行代理</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">wrapIfNecessary</span><span class="params">(Object bean, String beanName, Object cacheKey)</span> </span>&#123;</span><br><span class="line">     <span class="comment">// 如果已经处理过</span></span><br><span class="line">    <span class="keyword">if</span> (StringUtils.hasLength(beanName) &amp;&amp; <span class="keyword">this</span>.targetSourcedBeans.contains(beanName)) &#123;</span><br><span class="line">        <span class="keyword">return</span> bean;</span><br><span class="line">    &#125;</span><br><span class="line">     <span class="comment">// 无需增强</span></span><br><span class="line">    <span class="keyword">if</span> (Boolean.FALSE.equals(<span class="keyword">this</span>.advisedBeans.get(cacheKey))) &#123;</span><br><span class="line">        <span class="keyword">return</span> bean;</span><br><span class="line">    &#125;</span><br><span class="line">     <span class="comment">// 给定的bean如果是一个基础设施类或者配置了不需要自动代理，则不对其代理</span></span><br><span class="line">    <span class="keyword">if</span> (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) &#123;</span><br><span class="line">        <span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.FALSE);</span><br><span class="line">        <span class="keyword">return</span> bean;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create proxy if we have advice.</span></span><br><span class="line">    <span class="comment">// 获取当前bean的所有增强器（通知方法）</span></span><br><span class="line">    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, <span class="keyword">null</span>);</span><br><span class="line">    <span class="comment">// 如果有增强方法，则创建代理</span></span><br><span class="line">    <span class="keyword">if</span> (specificInterceptors != DO_NOT_PROXY) &#123;</span><br><span class="line">        <span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.TRUE);</span><br><span class="line">        <span class="comment">// 创建代理</span></span><br><span class="line">        Object proxy = createProxy(</span><br><span class="line">                bean.getClass(), beanName, specificInterceptors, <span class="keyword">new</span> SingletonTargetSource(bean));</span><br><span class="line">        <span class="keyword">this</span>.proxyTypes.put(cacheKey, proxy.getClass());</span><br><span class="line">        <span class="keyword">return</span> proxy;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.FALSE);</span><br><span class="line">    <span class="keyword">return</span> bean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h2 id="获取增强方法"><a href="#获取增强方法" class="headerlink" title="获取增强方法"></a>获取增强方法</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="keyword">protected</span> Object[] getAdvicesAndAdvisorsForBean(</span><br><span class="line">      Class&lt;?&gt; beanClass, String beanName, <span class="meta">@Nullable</span> TargetSource targetSource) &#123;</span><br><span class="line"></span><br><span class="line">   List&lt;Advisor&gt; advisors = findEligibleAdvisors(beanClass, beanName);</span><br><span class="line">   <span class="keyword">if</span> (advisors.isEmpty()) &#123;</span><br><span class="line">      <span class="keyword">return</span> DO_NOT_PROXY;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> advisors.toArray();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> List&lt;Advisor&gt; <span class="title">findEligibleAdvisors</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取所有的增强</span></span><br><span class="line">   List&lt;Advisor&gt; candidateAdvisors = findCandidateAdvisors();</span><br><span class="line">    <span class="comment">// 寻找所有增强中适用于当前bean的增强并应用</span></span><br><span class="line">   List&lt;Advisor&gt; eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);</span><br><span class="line">   extendAdvisors(eligibleAdvisors);</span><br><span class="line">   <span class="keyword">if</span> (!eligibleAdvisors.isEmpty()) &#123;</span><br><span class="line">      eligibleAdvisors = sortAdvisors(eligibleAdvisors);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> eligibleAdvisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="获取增强器"><a href="#获取增强器" class="headerlink" title="获取增强器"></a>获取增强器</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> List&lt;Advisor&gt; <span class="title">findCandidateAdvisors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Add all the Spring advisors found according to superclass rules.</span></span><br><span class="line">    List&lt;Advisor&gt; advisors = <span class="keyword">super</span>.findCandidateAdvisors();</span><br><span class="line">    <span class="comment">// Build Advisors for all AspectJ aspects in the bean factory.</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.aspectJAdvisorsBuilder != <span class="keyword">null</span>) &#123;</span><br><span class="line">        advisors.addAll(<span class="keyword">this</span>.aspectJAdvisorsBuilder.buildAspectJAdvisors());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>其中 <code>buildAspectJAdvisors</code> 方法实现如下：</p>
<ol>
<li>获取所有的beanname</li>
<li>遍历所有beanname，找出声明AspectJ的类</li>
<li>提取增强器</li>
<li>将提取结果存入缓存</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Advisor&gt; <span class="title">buildAspectJAdvisors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;String&gt; aspectNames = <span class="keyword">this</span>.aspectBeanNames;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            aspectNames = <span class="keyword">this</span>.aspectBeanNames;</span><br><span class="line">            <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">                List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">                aspectNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">                <span class="comment">// 获取所有beanname</span></span><br><span class="line">                String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(</span><br><span class="line">                        <span class="keyword">this</span>.beanFactory, Object.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">                <span class="comment">// 便利所有beanname，提取增强方法</span></span><br><span class="line">                <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (!isEligibleBean(beanName)) &#123;</span><br><span class="line">                        <span class="keyword">continue</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// We must be careful not to instantiate beans eagerly as in this case they</span></span><br><span class="line">                    <span class="comment">// would be cached by the Spring container but would not have been weaved.</span></span><br><span class="line">                    Class&lt;?&gt; beanType = <span class="keyword">this</span>.beanFactory.getType(beanName);</span><br><span class="line">                    <span class="keyword">if</span> (beanType == <span class="keyword">null</span>) &#123;</span><br><span class="line">                        <span class="keyword">continue</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// 被AspectJ修饰的类</span></span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">this</span>.advisorFactory.isAspect(beanType)) &#123;</span><br><span class="line">                        aspectNames.add(beanName);</span><br><span class="line">                        AspectMetadata amd = <span class="keyword">new</span> AspectMetadata(beanType, beanName);</span><br><span class="line">                        <span class="keyword">if</span> (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) &#123;</span><br><span class="line">                            MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                                    <span class="keyword">new</span> BeanFactoryAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                            <span class="comment">// 解析提取增强器</span></span><br><span class="line">                            List&lt;Advisor&gt; classAdvisors = <span class="keyword">this</span>.advisorFactory.getAdvisors(factory);</span><br><span class="line">                            <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                                <span class="keyword">this</span>.advisorsCache.put(beanName, classAdvisors);</span><br><span class="line">                            &#125;</span><br><span class="line">                            <span class="keyword">else</span> &#123;</span><br><span class="line">                                <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                            &#125;</span><br><span class="line">                            advisors.addAll(classAdvisors);</span><br><span class="line">                        &#125;</span><br><span class="line">                        <span class="keyword">else</span> &#123;</span><br><span class="line">                            <span class="comment">// Per target or per this.</span></span><br><span class="line">                            <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Bean with name &#x27;&quot;</span> + beanName +</span><br><span class="line">                                        <span class="string">&quot;&#x27; is a singleton, but aspect instantiation model is not singleton&quot;</span>);</span><br><span class="line">                            &#125;</span><br><span class="line">                            MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                                    <span class="keyword">new</span> PrototypeAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                            <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                            advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">this</span>.aspectBeanNames = aspectNames;</span><br><span class="line">                <span class="keyword">return</span> advisors;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (aspectNames.isEmpty()) &#123;</span><br><span class="line">        <span class="keyword">return</span> Collections.emptyList();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 记录在缓存中</span></span><br><span class="line">    List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">for</span> (String aspectName : aspectNames) &#123;</span><br><span class="line">        List&lt;Advisor&gt; cachedAdvisors = <span class="keyword">this</span>.advisorsCache.get(aspectName);</span><br><span class="line">        <span class="keyword">if</span> (cachedAdvisors != <span class="keyword">null</span>) &#123;</span><br><span class="line">            advisors.addAll(cachedAdvisors);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            MetadataAwareAspectInstanceFactory factory = <span class="keyword">this</span>.aspectFactoryCache.get(aspectName);</span><br><span class="line">            advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h4 id="增强器的获取"><a href="#增强器的获取" class="headerlink" title="增强器的获取"></a>增强器的获取</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Advisor&gt; <span class="title">getAdvisors</span><span class="params">(MetadataAwareAspectInstanceFactory aspectInstanceFactory)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取标记为AspectJ的类</span></span><br><span class="line">    Class&lt;?&gt; aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();</span><br><span class="line">    <span class="comment">// 获取标记为AspectJ的name</span></span><br><span class="line">    String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();</span><br><span class="line">    <span class="comment">// 验证</span></span><br><span class="line">    validate(aspectClass);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// We need to wrap the MetadataAwareAspectInstanceFactory with a decorator</span></span><br><span class="line">    <span class="comment">// so that it will only instantiate once.</span></span><br><span class="line">    MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =</span><br><span class="line">            <span class="keyword">new</span> LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);</span><br><span class="line"></span><br><span class="line">    List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">for</span> (Method method : getAdvisorMethods(aspectClass)) &#123;</span><br><span class="line">        <span class="comment">// 增强器的获取</span></span><br><span class="line">        Advisor advisor =</span><br><span class="line">                getAdvisor(</span><br><span class="line">                        method,</span><br><span class="line">                        lazySingletonAspectInstanceFactory,</span><br><span class="line">                        advisors.size(),</span><br><span class="line">                        aspectName);</span><br><span class="line">        <span class="keyword">if</span> (advisor != <span class="keyword">null</span>) &#123;</span><br><span class="line">            advisors.add(advisor);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// If it&#x27;s a per target aspect, emit the dummy instantiating aspect.</span></span><br><span class="line">    <span class="keyword">if</span> (!advisors.isEmpty()</span><br><span class="line">            &amp;&amp; lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) &#123;</span><br><span class="line">        <span class="comment">// 如果获取的增强器不为空并且配置了增强延迟初始化，那么需要在首位加入同步实例化增强器</span></span><br><span class="line">        Advisor instantiationAdvisor =</span><br><span class="line">                <span class="keyword">new</span> SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);</span><br><span class="line">        advisors.add(<span class="number">0</span>, instantiationAdvisor);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Find introduction fields.</span></span><br><span class="line">    <span class="comment">// 获取DeclareParent注解</span></span><br><span class="line">    <span class="keyword">for</span> (Field field : aspectClass.getDeclaredFields()) &#123;</span><br><span class="line">        Advisor advisor = getDeclareParentsAdvisor(field);</span><br><span class="line">        <span class="keyword">if</span> (advisor != <span class="keyword">null</span>) &#123;</span><br><span class="line">            advisors.add(advisor);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h5 id="普通增强器的获取"><a href="#普通增强器的获取" class="headerlink" title="普通增强器的获取"></a>普通增强器的获取</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Advisor <span class="title">getAdvisor</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Method candidateAdviceMethod,</span></span></span><br><span class="line"><span class="function"><span class="params">        MetadataAwareAspectInstanceFactory aspectInstanceFactory,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="keyword">int</span> declarationOrderInAspect,</span></span></span><br><span class="line"><span class="function"><span class="params">        String aspectName)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取切点信息</span></span><br><span class="line">    AspectJExpressionPointcut expressionPointcut =</span><br><span class="line">            getPointcut(</span><br><span class="line">                    candidateAdviceMethod,</span><br><span class="line">                    aspectInstanceFactory.getAspectMetadata().getAspectClass());</span><br><span class="line">    <span class="keyword">if</span> (expressionPointcut == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 根据切点信息生成增强器</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> InstantiationModelAwarePointcutAdvisorImpl(</span><br><span class="line">            expressionPointcut,</span><br><span class="line">            candidateAdviceMethod,</span><br><span class="line">            <span class="keyword">this</span>,</span><br><span class="line">            aspectInstanceFactory,</span><br><span class="line">            declarationOrderInAspect,</span><br><span class="line">            aspectName);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h6 id="切点信息的获取"><a href="#切点信息的获取" class="headerlink" title="切点信息的获取"></a>切点信息的获取</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> AspectJExpressionPointcut <span class="title">getPointcut</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Method candidateAdviceMethod, Class&lt;?&gt; candidateAspectClass)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取方法上的注解</span></span><br><span class="line">    AspectJAnnotation&lt;?&gt; aspectJAnnotation =</span><br><span class="line">            AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);</span><br><span class="line">    <span class="keyword">if</span> (aspectJAnnotation == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    AspectJExpressionPointcut ajexp =</span><br><span class="line">            <span class="keyword">new</span> AspectJExpressionPointcut(candidateAspectClass, <span class="keyword">new</span> String[<span class="number">0</span>], <span class="keyword">new</span> Class&lt;?&gt;[<span class="number">0</span>]);</span><br><span class="line">    <span class="comment">// 提取得到的注解中的表达式（execution）</span></span><br><span class="line">    ajexp.setExpression(aspectJAnnotation.getPointcutExpression());</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">        ajexp.setBeanFactory(<span class="keyword">this</span>.beanFactory);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ajexp;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 注解的获取：敏感的注解类 */</span></span><br><span class="line"><span class="keyword">protected</span> <span class="keyword">static</span> AspectJAnnotation&lt;?&gt; findAspectJAnnotationOnMethod(Method method) &#123;</span><br><span class="line">    <span class="comment">// private static final Class&lt;?&gt;[] ASPECTJ_ANNOTATION_CLASSES = new Class&lt;?&gt;[] &#123;</span></span><br><span class="line">    <span class="comment">//       Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class,</span></span><br><span class="line">    <span class="comment">// AfterThrowing.class&#125;;</span></span><br><span class="line">    <span class="comment">// 敏感的注解类</span></span><br><span class="line">    <span class="keyword">for</span> (Class&lt;?&gt; clazz : ASPECTJ_ANNOTATION_CLASSES) &#123;</span><br><span class="line">        AspectJAnnotation&lt;?&gt; foundAnnotation =</span><br><span class="line">                findAnnotation(method, (Class&lt;Annotation&gt;) clazz);</span><br><span class="line">        <span class="keyword">if</span> (foundAnnotation != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> foundAnnotation;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 获取指定方法上的注解并使用AspectJAnnotation封装 */</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> &lt;A extends Annotation&gt; <span class="function">AspectJAnnotation&lt;A&gt; <span class="title">findAnnotation</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Method method, Class&lt;A&gt; toLookFor)</span> </span>&#123;</span><br><span class="line">    A result = AnnotationUtils.findAnnotation(method, toLookFor);</span><br><span class="line">    <span class="keyword">if</span> (result != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> AspectJAnnotation&lt;&gt;(result);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h6 id="根据切点信息生成增强"><a href="#根据切点信息生成增强" class="headerlink" title="根据切点信息生成增强"></a>根据切点信息生成增强</h6><p>spring会跟据不同的注解生成不同的增强器（只放部分）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">switch</span> (aspectJAnnotation.getAnnotationType()) &#123;</span><br><span class="line">    <span class="keyword">case</span> AtPointcut:</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">&quot;Processing pointcut &#x27;&quot;</span> + candidateAdviceMethod.getName() + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">case</span> AtAround:</span><br><span class="line">        springAdvice =</span><br><span class="line">                <span class="keyword">new</span> AspectJAroundAdvice(</span><br><span class="line">                        candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> AtBefore:</span><br><span class="line">        springAdvice =</span><br><span class="line">                <span class="keyword">new</span> AspectJMethodBeforeAdvice(</span><br><span class="line">                        candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> AtAfter:</span><br><span class="line">        springAdvice =</span><br><span class="line">                <span class="keyword">new</span> AspectJAfterAdvice(</span><br><span class="line">                        candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> AtAfterReturning:</span><br><span class="line">        springAdvice =</span><br><span class="line">                <span class="keyword">new</span> AspectJAfterReturningAdvice(</span><br><span class="line">                        candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);</span><br><span class="line">        AfterReturning afterReturningAnnotation =</span><br><span class="line">                (AfterReturning) aspectJAnnotation.getAnnotation();</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.hasText(afterReturningAnnotation.returning())) &#123;</span><br><span class="line">            springAdvice.setReturningName(afterReturningAnnotation.returning());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> AtAfterThrowing:</span><br><span class="line">        springAdvice =</span><br><span class="line">                <span class="keyword">new</span> AspectJAfterThrowingAdvice(</span><br><span class="line">                        candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);</span><br><span class="line">        AfterThrowing afterThrowingAnnotation =</span><br><span class="line">                (AfterThrowing) aspectJAnnotation.getAnnotation();</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.hasText(afterThrowingAnnotation.throwing())) &#123;</span><br><span class="line">            springAdvice.setThrowingName(afterThrowingAnnotation.throwing());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> UnsupportedOperationException(</span><br><span class="line">                <span class="string">&quot;Unsupported advice type on method: &quot;</span> + candidateAdviceMethod);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h5 id="寻找匹配的增强器"><a href="#寻找匹配的增强器" class="headerlink" title="寻找匹配的增强器"></a>寻找匹配的增强器</h5><p>对于所有的增强器来讲，不一定都适用于当前的bean，还要挑取出适合的增强器，也就是满足我们配置的通配符的增强器。</p>
<h2 id="创建代理"><a href="#创建代理" class="headerlink" title="创建代理"></a>创建代理</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createProxy</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Class&lt;?&gt; beanClass,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="meta">@Nullable</span> String beanName,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="meta">@Nullable</span> Object[] specificInterceptors,</span></span></span><br><span class="line"><span class="function"><span class="params">        TargetSource targetSource)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory <span class="keyword">instanceof</span> ConfigurableListableBeanFactory) &#123;</span><br><span class="line">        AutoProxyUtils.exposeTargetClass(</span><br><span class="line">                (ConfigurableListableBeanFactory) <span class="keyword">this</span>.beanFactory, beanName, beanClass);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ProxyFactory proxyFactory = <span class="keyword">new</span> ProxyFactory();</span><br><span class="line">    <span class="comment">// 获取当前类中相关属性</span></span><br><span class="line">    proxyFactory.copyFrom(<span class="keyword">this</span>);</span><br><span class="line">    <span class="comment">// 决定对于给定的bean是否应该使用targetClass而不是他的接口代理</span></span><br><span class="line">    <span class="comment">// 检查proxyTargetClass设置以及preserveTargetClass属性</span></span><br><span class="line">    <span class="keyword">if</span> (!proxyFactory.isProxyTargetClass()) &#123;</span><br><span class="line">        <span class="keyword">if</span> (shouldProxyTargetClass(beanClass, beanName)) &#123;</span><br><span class="line">            proxyFactory.setProxyTargetClass(<span class="keyword">true</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 添加代理接口</span></span><br><span class="line">            evaluateProxyInterfaces(beanClass, proxyFactory);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 封装增强器（将拦截器封装转化为Advisor）并加入到代理工厂中</span></span><br><span class="line">    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);</span><br><span class="line">    proxyFactory.addAdvisors(advisors);</span><br><span class="line">    <span class="comment">// 设置要代理的类</span></span><br><span class="line">    proxyFactory.setTargetSource(targetSource);</span><br><span class="line">    <span class="comment">// 定制函数，为子类使用</span></span><br><span class="line">    customizeProxyFactory(proxyFactory);</span><br><span class="line">    <span class="comment">// 用来控制代理工厂被配置之后是否还允许修改通知，默认false，即不允许</span></span><br><span class="line">    proxyFactory.setFrozen(<span class="keyword">this</span>.freezeProxy);</span><br><span class="line">    <span class="keyword">if</span> (advisorsPreFiltered()) &#123;</span><br><span class="line">        proxyFactory.setPreFiltered(<span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 获取代理</span></span><br><span class="line">    <span class="keyword">return</span> proxyFactory.getProxy(getProxyClassLoader());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(<span class="meta">@Nullable</span> ClassLoader classLoader)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 创建代理 + 获取代理</span></span><br><span class="line">    <span class="keyword">return</span> createAopProxy().getProxy(classLoader);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="创建代理-1"><a href="#创建代理-1" class="headerlink" title="创建代理"></a>创建代理</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">synchronized</span> AopProxy <span class="title">createAopProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.active) &#123;</span><br><span class="line">        activate();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 创建代理</span></span><br><span class="line">    <span class="keyword">return</span> getAopProxyFactory().createAopProxy(<span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> AopProxy <span class="title">createAopProxy</span><span class="params">(AdvisedSupport config)</span> <span class="keyword">throws</span> AopConfigException </span>&#123;</span><br><span class="line">    <span class="comment">// 代理方法的选择</span></span><br><span class="line">    <span class="keyword">if</span> (config.isOptimize() <span class="comment">// 用于控制通过cglib创建的代理是否使用激进的优化策略（暂不做了解</span></span><br><span class="line">            || config.isProxyTargetClass() <span class="comment">// proxy-target-class 属性值（为true则目标类本身被代理而不是目标类的接口）</span></span><br><span class="line">            || hasNoUserSuppliedProxyInterfaces(config)) &#123; <span class="comment">// 是否存在代理接口</span></span><br><span class="line">        Class&lt;?&gt; targetClass = config.getTargetClass();</span><br><span class="line">        <span class="keyword">if</span> (targetClass == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> AopConfigException(</span><br><span class="line">                    <span class="string">&quot;TargetSource cannot determine target class: &quot;</span></span><br><span class="line">                            + <span class="string">&quot;Either an interface or a target is required for proxy creation.&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> JdkDynamicAopProxy(config);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ObjenesisCglibAopProxy(config);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 返回jdk动态代理</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> JdkDynamicAopProxy(config);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="获取代理"><a href="#获取代理" class="headerlink" title="获取代理"></a>获取代理</h3><h4 id="jdk动态代理-—-JdkDynamicAopProxy-java"><a href="#jdk动态代理-—-JdkDynamicAopProxy-java" class="headerlink" title="jdk动态代理 — JdkDynamicAopProxy.java"></a>jdk动态代理 — JdkDynamicAopProxy.java</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> getProxy(ClassUtils.getDefaultClassLoader());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(<span class="meta">@Nullable</span> ClassLoader classLoader)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">        logger.trace(<span class="string">&quot;Creating JDK dynamic proxy: &quot;</span> + <span class="keyword">this</span>.advised.getTargetSource());</span><br><span class="line">    &#125;</span><br><span class="line">    Class&lt;?&gt;[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(<span class="keyword">this</span>.advised, <span class="keyword">true</span>);</span><br><span class="line">    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);</span><br><span class="line">    <span class="keyword">return</span> Proxy.newProxyInstance(classLoader, proxiedInterfaces, <span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 主要是完成了一个拦截器链的创建及封装，在其proceed方法中实现了拦截器的逐一调用 */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">    Object oldProxy = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">boolean</span> setProxyContext = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    TargetSource targetSource = <span class="keyword">this</span>.advised.targetSource;</span><br><span class="line">    Object target = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// equal方法的处理</span></span><br><span class="line">        <span class="keyword">if</span> (!<span class="keyword">this</span>.equalsDefined &amp;&amp; AopUtils.isEqualsMethod(method)) &#123;</span><br><span class="line">            <span class="comment">// The target does not implement the equals(Object) method itself.</span></span><br><span class="line">            <span class="keyword">return</span> equals(args[<span class="number">0</span>]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// hash方法的处理</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (!<span class="keyword">this</span>.hashCodeDefined &amp;&amp; AopUtils.isHashCodeMethod(method)) &#123;</span><br><span class="line">            <span class="comment">// The target does not implement the hashCode() method itself.</span></span><br><span class="line">            <span class="keyword">return</span> hashCode();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (method.getDeclaringClass() == DecoratingProxy.class) &#123;</span><br><span class="line">            <span class="comment">// There is only getDecoratedClass() declared -&gt; dispatch to proxy config.</span></span><br><span class="line">            <span class="keyword">return</span> AopProxyUtils.ultimateTargetClass(<span class="keyword">this</span>.advised);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!<span class="keyword">this</span>.advised.opaque</span><br><span class="line">                &amp;&amp; method.getDeclaringClass().isInterface()</span><br><span class="line">                &amp;&amp; method.getDeclaringClass().isAssignableFrom(Advised.class)) &#123;</span><br><span class="line">            <span class="comment">// Service invocations on ProxyConfig with the proxy config...</span></span><br><span class="line">            <span class="keyword">return</span> AopUtils.invokeJoinpointUsingReflection(<span class="keyword">this</span>.advised, method, args);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Object retVal;</span><br><span class="line">        <span class="comment">// 有时候目标对象内部的自我调用将无法实施切面中的增强则需要通过此属性暴露代理</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.advised.exposeProxy) &#123;</span><br><span class="line">            <span class="comment">// Make invocation available if necessary.</span></span><br><span class="line">            oldProxy = AopContext.setCurrentProxy(proxy);</span><br><span class="line">            setProxyContext = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Get as late as possible to minimize the time we &quot;own&quot; the target,</span></span><br><span class="line">        <span class="comment">// in case it comes from a pool.</span></span><br><span class="line">        target = targetSource.getTarget();</span><br><span class="line">        Class&lt;?&gt; targetClass = (target != <span class="keyword">null</span> ? target.getClass() : <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Get the interception chain for this method.</span></span><br><span class="line">        <span class="comment">// 获取该方法的拦截器链</span></span><br><span class="line">        List&lt;Object&gt; chain =</span><br><span class="line">                <span class="keyword">this</span>.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Check whether we have any advice. If we don&#x27;t, we can fallback on direct</span></span><br><span class="line">        <span class="comment">// reflective invocation of the target, and avoid creating a MethodInvocation.</span></span><br><span class="line">        <span class="keyword">if</span> (chain.isEmpty()) &#123;</span><br><span class="line">            <span class="comment">// We can skip creating a MethodInvocation: just invoke the target directly</span></span><br><span class="line">            <span class="comment">// Note that the final invoker must be an InvokerInterceptor so we know it does</span></span><br><span class="line">            <span class="comment">// nothing but a reflective operation on the target, and no hot swapping or fancy</span></span><br><span class="line">            <span class="comment">// proxying.</span></span><br><span class="line">            <span class="comment">// 如果没有发现任何拦截器那么直接调用切点方法</span></span><br><span class="line">            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);</span><br><span class="line">            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// We need to create a method invocation...</span></span><br><span class="line">            <span class="comment">// 封装拦截器以便于</span></span><br><span class="line">            MethodInvocation invocation =</span><br><span class="line">                    <span class="keyword">new</span> ReflectiveMethodInvocation(</span><br><span class="line">                            proxy, target, method, args, targetClass, chain);</span><br><span class="line">            <span class="comment">// Proceed to the joinpoint through the interceptor chain.</span></span><br><span class="line">            <span class="comment">// 执行拦截器</span></span><br><span class="line">            retVal = invocation.proceed();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Massage return value if necessary.</span></span><br><span class="line">        Class&lt;?&gt; returnType = method.getReturnType();</span><br><span class="line">        <span class="comment">// 返回结果</span></span><br><span class="line">        <span class="keyword">if</span> (retVal != <span class="keyword">null</span></span><br><span class="line">                &amp;&amp; retVal == target</span><br><span class="line">                &amp;&amp; returnType != Object.class</span><br><span class="line">                &amp;&amp; returnType.isInstance(proxy)</span><br><span class="line">                &amp;&amp; !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) &#123;</span><br><span class="line">            <span class="comment">// Special case: it returned &quot;this&quot; and the return type of the method</span></span><br><span class="line">            <span class="comment">// is type-compatible. Note that we can&#x27;t help if the target sets</span></span><br><span class="line">            <span class="comment">// a reference to itself in another returned object.</span></span><br><span class="line">            retVal = proxy;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (retVal == <span class="keyword">null</span> &amp;&amp; returnType != Void.TYPE &amp;&amp; returnType.isPrimitive()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> AopInvocationException(</span><br><span class="line">                    <span class="string">&quot;Null return value from advice does not match primitive return type for: &quot;</span></span><br><span class="line">                            + method);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> retVal;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (target != <span class="keyword">null</span> &amp;&amp; !targetSource.isStatic()) &#123;</span><br><span class="line">            <span class="comment">// Must have come from TargetSource.</span></span><br><span class="line">            targetSource.releaseTarget(target);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (setProxyContext) &#123;</span><br><span class="line">            <span class="comment">// Restore old proxy.</span></span><br><span class="line">            AopContext.setCurrentProxy(oldProxy);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>proceed()：拦截器的调用</p>
<p>主要是维护了一个链接调用的计数器，记录当前调用链接的位置，以便链可以有序地进行下去</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">proceed</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">    <span class="comment">// We start with an index of -1 and increment early.</span></span><br><span class="line">    <span class="comment">// 执行完所有增强后执行切点方法</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.currentInterceptorIndex == <span class="keyword">this</span>.interceptorsAndDynamicMethodMatchers.size() - <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> invokeJoinpoint();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取下一个要执行的方法</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Index from 0 of the current interceptor we&#x27;re invoking. -1 until we invoke: then the</span></span><br><span class="line"><span class="comment">     * current interceptor. 维护了链接调用的计数器，记录了当前调用链接的位置</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;private int currentInterceptorIndex = -1;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    Object interceptorOrInterceptionAdvice =</span><br><span class="line">            <span class="keyword">this</span>.interceptorsAndDynamicMethodMatchers.get(++<span class="keyword">this</span>.currentInterceptorIndex);</span><br><span class="line">    <span class="keyword">if</span> (interceptorOrInterceptionAdvice <span class="keyword">instanceof</span> InterceptorAndDynamicMethodMatcher) &#123;</span><br><span class="line">        <span class="comment">// Evaluate dynamic method matcher here: static part will already have</span></span><br><span class="line">        <span class="comment">// been evaluated and found to match.</span></span><br><span class="line">        <span class="comment">// 动态匹配</span></span><br><span class="line">        InterceptorAndDynamicMethodMatcher dm =</span><br><span class="line">                (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;</span><br><span class="line">        Class&lt;?&gt; targetClass =</span><br><span class="line">                (<span class="keyword">this</span>.targetClass != <span class="keyword">null</span> ? <span class="keyword">this</span>.targetClass : <span class="keyword">this</span>.method.getDeclaringClass());</span><br><span class="line">        <span class="keyword">if</span> (dm.methodMatcher.matches(<span class="keyword">this</span>.method, targetClass, <span class="keyword">this</span>.arguments)) &#123;</span><br><span class="line">            <span class="keyword">return</span> dm.interceptor.invoke(<span class="keyword">this</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Dynamic matching failed.</span></span><br><span class="line">            <span class="comment">// Skip this interceptor and invoke the next in the chain.</span></span><br><span class="line">            <span class="comment">// 不匹配则不执行拦截器</span></span><br><span class="line">            <span class="keyword">return</span> proceed();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// It&#x27;s an interceptor, so we just invoke it: The pointcut will have</span></span><br><span class="line">        <span class="comment">// been evaluated statically before this object was constructed.</span></span><br><span class="line">        <span class="comment">// 普通拦截器，直接调用</span></span><br><span class="line">        <span class="keyword">return</span> ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(<span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h4 id="cglib代理-—-CglibAopProxy-java"><a href="#cglib代理-—-CglibAopProxy-java" class="headerlink" title="cglib代理 — CglibAopProxy.java"></a>cglib代理 — CglibAopProxy.java</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(<span class="meta">@Nullable</span> ClassLoader classLoader)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">        logger.trace(<span class="string">&quot;Creating CGLIB proxy: &quot;</span> + <span class="keyword">this</span>.advised.getTargetSource());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Class&lt;?&gt; rootClass = <span class="keyword">this</span>.advised.getTargetClass();</span><br><span class="line">        Assert.state(</span><br><span class="line">                rootClass != <span class="keyword">null</span>, <span class="string">&quot;Target class must be available for creating a CGLIB proxy&quot;</span>);</span><br><span class="line"></span><br><span class="line">        Class&lt;?&gt; proxySuperClass = rootClass;</span><br><span class="line">        <span class="keyword">if</span> (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) &#123;</span><br><span class="line">            proxySuperClass = rootClass.getSuperclass();</span><br><span class="line">            Class&lt;?&gt;[] additionalInterfaces = rootClass.getInterfaces();</span><br><span class="line">            <span class="keyword">for</span> (Class&lt;?&gt; additionalInterface : additionalInterfaces) &#123;</span><br><span class="line">                <span class="keyword">this</span>.advised.addInterface(additionalInterface);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Validate the class, writing log messages as necessary.</span></span><br><span class="line">        <span class="comment">// 验证Class</span></span><br><span class="line">        validateClassIfNecessary(proxySuperClass, classLoader);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Configure CGLIB Enhancer...</span></span><br><span class="line">        <span class="comment">// 创建并配置Enhancer</span></span><br><span class="line">        Enhancer enhancer = createEnhancer();</span><br><span class="line">        <span class="keyword">if</span> (classLoader != <span class="keyword">null</span>) &#123;</span><br><span class="line">            enhancer.setClassLoader(classLoader);</span><br><span class="line">            <span class="keyword">if</span> (classLoader <span class="keyword">instanceof</span> SmartClassLoader</span><br><span class="line">                    &amp;&amp; ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) &#123;</span><br><span class="line">                enhancer.setUseCache(<span class="keyword">false</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        enhancer.setSuperclass(proxySuperClass);</span><br><span class="line">        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(<span class="keyword">this</span>.advised));</span><br><span class="line">        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);</span><br><span class="line">        enhancer.setStrategy(<span class="keyword">new</span> ClassLoaderAwareGeneratorStrategy(classLoader));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取拦截器链并封装加入Callback中</span></span><br><span class="line">        Callback[] callbacks = getCallbacks(rootClass);</span><br><span class="line">        Class&lt;?&gt;[] types = <span class="keyword">new</span> Class&lt;?&gt;[callbacks.length];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> x = <span class="number">0</span>; x &lt; types.length; x++) &#123;</span><br><span class="line">            types[x] = callbacks[x].getClass();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// fixedInterceptorMap only populated at this point, after getCallbacks call above</span></span><br><span class="line">        enhancer.setCallbackFilter(</span><br><span class="line">                <span class="keyword">new</span> ProxyCallbackFilter(</span><br><span class="line">                        <span class="keyword">this</span>.advised.getConfigurationOnlyCopy(),</span><br><span class="line">                        <span class="keyword">this</span>.fixedInterceptorMap,</span><br><span class="line">                        <span class="keyword">this</span>.fixedInterceptorOffset));</span><br><span class="line">        enhancer.setCallbackTypes(types);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Generate the proxy class and create a proxy instance.</span></span><br><span class="line">        <span class="keyword">return</span> createProxyClassAndInstance(enhancer, callbacks);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (CodeGenerationException | IllegalArgumentException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> AopConfigException(</span><br><span class="line">                <span class="string">&quot;Could not generate CGLIB subclass of &quot;</span></span><br><span class="line">                        + <span class="keyword">this</span>.advised.getTargetClass()</span><br><span class="line">                        + <span class="string">&quot;: Common causes of this problem include using a final class or a non-visible class&quot;</span>,</span><br><span class="line">                ex);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">        <span class="comment">// TargetSource.getTarget() failed</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> AopConfigException(<span class="string">&quot;Unexpected AOP exception&quot;</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createProxyClassAndInstance</span><span class="params">(Enhancer enhancer, Callback[] callbacks)</span> </span>&#123;</span><br><span class="line">    enhancer.setInterceptDuringConstruction(<span class="keyword">false</span>);</span><br><span class="line">    <span class="comment">// 设置拦截器</span></span><br><span class="line">    enhancer.setCallbacks(callbacks);</span><br><span class="line">    <span class="comment">// 生成代理类以及创建代理并返回</span></span><br><span class="line">    <span class="keyword">return</span> (<span class="keyword">this</span>.constructorArgs != <span class="keyword">null</span> &amp;&amp; <span class="keyword">this</span>.constructorArgTypes != <span class="keyword">null</span></span><br><span class="line">            ? enhancer.create(<span class="keyword">this</span>.constructorArgTypes, <span class="keyword">this</span>.constructorArgs)</span><br><span class="line">            : enhancer.create());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>其中提到</p>
<blockquote>
<p>// 获取拦截器链并封装加入Callback中</p>
<p>Callback[] callbacks = getCallbacks(rootClass);</p>
</blockquote>
<p>这是因为cglib对于方法的拦截是通过将自定义的拦截器（实现MethodInterceptor接口）加入Callback中并在调用代理时直接激活拦截器中的intercept方法来实现的，将拦截器封装在DynamicAdvisedInterceptor（继承了MethodInterceptor）并加入到callbacks中，那么在再次调用代理是会直接调用intercept方法。</p>
<h5 id="intercept"><a href="#intercept" class="headerlink" title="intercept"></a>intercept</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object proxy, Method method, Object[] args, MethodProxy methodProxy)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">    Object oldProxy = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">boolean</span> setProxyContext = <span class="keyword">false</span>;</span><br><span class="line">    Object target = <span class="keyword">null</span>;</span><br><span class="line">    TargetSource targetSource = <span class="keyword">this</span>.advised.getTargetSource();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.advised.exposeProxy) &#123;</span><br><span class="line">            <span class="comment">// Make invocation available if necessary.</span></span><br><span class="line">            oldProxy = AopContext.setCurrentProxy(proxy);</span><br><span class="line">            setProxyContext = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Get as late as possible to minimize the time we &quot;own&quot; the target, in case it</span></span><br><span class="line">        <span class="comment">// comes from a pool...</span></span><br><span class="line">        target = targetSource.getTarget();</span><br><span class="line">        Class&lt;?&gt; targetClass = (target != <span class="keyword">null</span> ? target.getClass() : <span class="keyword">null</span>);</span><br><span class="line">        <span class="comment">// 获取拦截器链</span></span><br><span class="line">        <span class="comment">// 遍历所有增强器，将其转化为Interceptor</span></span><br><span class="line">        List&lt;Object&gt; chain =</span><br><span class="line">                <span class="keyword">this</span>.advised.getInterceptorsAndDynamicInterceptionAdvice(</span><br><span class="line">                        method, targetClass);</span><br><span class="line">        Object retVal;</span><br><span class="line">        <span class="comment">// Check whether we only have one InvokerInterceptor: that is,</span></span><br><span class="line">        <span class="comment">// no real advice, but just reflective invocation of the target.</span></span><br><span class="line">        <span class="keyword">if</span> (chain.isEmpty() &amp;&amp; Modifier.isPublic(method.getModifiers())) &#123;</span><br><span class="line">            <span class="comment">// 拦截器为空则直接激活原方法</span></span><br><span class="line">            <span class="comment">// We can skip creating a MethodInvocation: just invoke the target directly.</span></span><br><span class="line">            <span class="comment">// Note that the final invoker must be an InvokerInterceptor, so we know</span></span><br><span class="line">            <span class="comment">// it does nothing but a reflective operation on the target, and no hot</span></span><br><span class="line">            <span class="comment">// swapping or fancy proxying.</span></span><br><span class="line">            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);</span><br><span class="line">            retVal = methodProxy.invoke(target, argsToUse);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// We need to create a method invocation...</span></span><br><span class="line">            <span class="comment">// 进入链</span></span><br><span class="line">            retVal = <span class="keyword">new</span> CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();</span><br><span class="line">        &#125;</span><br><span class="line">        retVal = processReturnType(proxy, target, method, retVal);</span><br><span class="line">        <span class="keyword">return</span> retVal;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (target != <span class="keyword">null</span> &amp;&amp; !targetSource.isStatic()) &#123;</span><br><span class="line">            targetSource.releaseTarget(target);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (setProxyContext) &#123;</span><br><span class="line">            <span class="comment">// Restore old proxy.</span></span><br><span class="line">            AopContext.setCurrentProxy(oldProxy);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="链式调用，牛逼！"><a href="#链式调用，牛逼！" class="headerlink" title="链式调用，牛逼！"></a>链式调用，牛逼！</h6><p><img src="https://typora-yayako.oss-cn-hangzhou.aliyuncs.com/1594305527712-0c5c87e5-026e-466d-9354-7c7498314f44.png" class="lazyload" data-srcset="https://typora-yayako.oss-cn-hangzhou.aliyuncs.com/1594305527712-0c5c87e5-026e-466d-9354-7c7498314f44.png" srcset="" alt="image.png"></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>aop是在不改变原有业务逻辑的情况下，将横向逻辑切入到原有的业务逻辑中，根本上解耦，降低代码重复度。</p>
<h2 id="口头梳理"><a href="#口头梳理" class="headerlink" title="口头梳理"></a>口头梳理</h2><p>在实例化bean的实例化前置处理中针对需要被代理的bean进行代理。主要就是<strong>获取增强</strong>和<strong>创建代理</strong>两个步骤。</p>
<p><strong>获取增强器：</strong>在所有的beanname中找出声明AspectJ的类并提取其增强器存入缓存，通过从标记为AspectJ的类中的注解获取切点信息，并根据切点的注解信息获得对应的增强器（@Before、@After等）。</p>
<p><strong>创建代理：</strong>首先进行准备工作包括获取类的属性/代理接口的添加/增强器的封装/代理类的设置等，然后进行代理的获取工作，最开始就是选择代理方法（主要是根据cglib的一个优化策略、proxy-target-class属性、目标类是否存在代理接口三点来进行判断）。</p>
<ul>
<li>如果是<strong>jdk动态代理</strong>，在getProxy中获取到代理后，进入invoke函数进行代理操作，获取拦截器链并一一通过proceed函数执行（维护了一个链接调用的计数器，记录了当前调用链接的位置），如果没有拦截器则直接执行切点方法。</li>
<li>如果是<strong>cglib代理</strong>，在getProxy中创建并配置完enhancer后，同jdk动态代理一样也是先构造拦截器链然后封装串联调用。区别在于前者使用CglibMethodInvocation，继承自ReflectiveMethodInvocation，拦截器的核心执行就在其intercept函数中，而后者则是直接构造ReflectiveMethodInvocation，并重写其proceed函数进行拦截器的执行。</li>
</ul>
<h2 id="简单总结"><a href="#简单总结" class="headerlink" title="简单总结"></a>简单总结</h2><ol>
<li>获取当前bean的所有增强器（通知方法）<ol>
<li>找到候选的所有增强器（找哪些方法是需要切入当前bean方法的）</li>
<li>获取能在bean使用的增强器</li>
<li>给增强器排序</li>
</ol>
</li>
<li>保存当前bean在adviseBeans中</li>
<li>如果当前bean需要增强，创建当前bean的代理对象<ol>
<li>获取所有增强器（通知方法）</li>
<li>保存到proxyFactory</li>
<li>创建代理对象，默认情况下由spring决定使用jdk动态代理还是cglib代理</li>
</ol>
</li>
<li>给容器返回代理对象</li>
<li>执行方法<ol>
<li>intercept()拦截目标方法的执行</li>
<li>根据目标方法获取拦截器链</li>
<li>proceed()执行拦截器链和目标方法（维护了一个索引记录当前执行的拦截器）<ol>
<li>链式获取每一个拦截器，拦截器执行invoke方法，每一个拦截器等待下一个拦截器执行完成返回以后再来执行；拦截器链的机制保证通知方法与目标方法的执行顺序。</li>
</ol>
</li>
</ol>
</li>
</ol>

  
  
    
    <div class='footer'>
      
      
      
        <div class='copyright'>
          <blockquote>
            
              
                <p>博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</p>

              
            
              
                <p>本文永久链接是：<a href=https://www.yayako.cn/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/>https://www.yayako.cn/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/</a></p>
              
            
          </blockquote>
        </div>
      
      
    </div>
  
  
    


  <div class='article-meta' id="bottom">
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2021-01-23T00:19:49+08:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：2021年1月23日</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/tags/%E6%BA%90%E7%A0%81/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>源码</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/tags/Spring/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>Spring</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://www.yayako.cn/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/&title=Spring AOP 源码解析 - Yayako's Blog&summary=jdk动态代理与cglib代理的简单区别？Spring实现aop的流程？"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" srcset="">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://www.yayako.cn/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/&title=Spring AOP 源码解析 - Yayako's Blog&summary=jdk动态代理与cglib代理的简单区别？Spring实现aop的流程？"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" srcset="">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://service.weibo.com/share/share.php?url=https://www.yayako.cn/2020/06/07/Spring%20AOP%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/&title=Spring AOP 源码解析 - Yayako's Blog&summary=jdk动态代理与cglib代理的简单区别？Spring实现aop的流程？"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" srcset="">
          
        </a>
      
    
      
    
      
    
  </div>
</div>



        
      
    </div>
  </div>


  
  

  
    <div class="prev-next">
      
        <a class='prev' href='/2020/06/08/HashMap/'>
          <p class='title'><i class="fas fa-chevron-left" aria-hidden="true"></i>HashMap源码解析</p>
          <p class='content'>数据结构jdk1.7    数组 + 链表
jdk1.8    数组 + 链表 + 红黑树
当一个结点的链表长度大于8时，链表会转换成红黑树，提高查询效率,而链表长度小于6时又会退化成链表。
为...</p>
        </a>
      
      
        <a class='next' href='/2020/06/07/Spring%20Bean%E5%8A%A0%E8%BD%BD%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/'>
          <p class='title'>Spring Bean加载 源码解析<i class="fas fa-chevron-right" aria-hidden="true"></i></p>
          <p class='content'>主要参考了《Spring源码深度解析》这本书。
1234public &lt;T&gt; T getBean(String name, @Nullable Class&lt;T&gt; requ...</p>
        </a>
      
    </div>
  
</article>


  

  <article class="post white-box reveal shadow" id="comments">
    <p ct><i class='fas fa-comments'></i> 评论</p>
    
    <div id="valine_container" class="valine_thread">
  <i class="fas fa-cog fa-spin fa-fw fa-2x"></i>
</div>

  </article>






</div>
<aside class='l_side'>
  
  
    
    



  <section class="widget toc-wrapper shadow desktop mobile" id="toc-div" >
    
  <header>
    
      <i class="fas fa-list fa-fw" aria-hidden="true"></i><span class='name'>本文目录</span>
    
  </header>


    <div class='content'>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#jdk%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="toc-text">jdk动态代理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#cglib%E4%BB%A3%E7%90%86"><span class="toc-text">cglib代理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E4%BB%A3%E7%90%86"><span class="toc-text">静态代理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E5%A2%9E%E5%BC%BA%E6%96%B9%E6%B3%95"><span class="toc-text">获取增强方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E5%A2%9E%E5%BC%BA%E5%99%A8"><span class="toc-text">获取增强器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A2%9E%E5%BC%BA%E5%99%A8%E7%9A%84%E8%8E%B7%E5%8F%96"><span class="toc-text">增强器的获取</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%99%AE%E9%80%9A%E5%A2%9E%E5%BC%BA%E5%99%A8%E7%9A%84%E8%8E%B7%E5%8F%96"><span class="toc-text">普通增强器的获取</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AF%BB%E6%89%BE%E5%8C%B9%E9%85%8D%E7%9A%84%E5%A2%9E%E5%BC%BA%E5%99%A8"><span class="toc-text">寻找匹配的增强器</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E4%BB%A3%E7%90%86"><span class="toc-text">创建代理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E4%BB%A3%E7%90%86-1"><span class="toc-text">创建代理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E4%BB%A3%E7%90%86"><span class="toc-text">获取代理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#jdk%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86-%E2%80%94-JdkDynamicAopProxy-java"><span class="toc-text">jdk动态代理 — JdkDynamicAopProxy.java</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#cglib%E4%BB%A3%E7%90%86-%E2%80%94-CglibAopProxy-java"><span class="toc-text">cglib代理 — CglibAopProxy.java</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#intercept"><span class="toc-text">intercept</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%A3%E5%A4%B4%E6%A2%B3%E7%90%86"><span class="toc-text">口头梳理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E6%80%BB%E7%BB%93"><span class="toc-text">简单总结</span></a></li></ol>
    </div>
  </section>


  


</aside>


   <!--此文件用来存放一些不方便取值的变量-->
<!--思路大概是将值藏到重加载的区域内-->

<script>
  window.pdata={}
  pdata.ispage=true;
  pdata.postTitle="Spring AOP 源码解析";
  pdata.commentPath="";
  pdata.commentPlaceholder="";

  var l_header=document.getElementById("l_header");
  
  l_header.classList.remove("show");
  
</script>
 
        </div>
        
  
  <footer class="footer clearfix">
    <br><br>
    
      
        <div class="aplayer-container">
          


        </div>
      
    
      
        <br>
        <div class="social-wrapper">
          
            
          
            
          
            
          
        </div>
      
    
      
        <div><p>博客内容遵循 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</a></p>
</div>
      
    
      
        
          <div><p><span id="lc-sv">本站总访问量为 <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 次</span> <span id="lc-uv">访客数为 <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 人</span></p>
</div>
        
      
    
      
        
      
    
      
        <div class='copyright'>
        <p><a href="/about/">Copyright © 2021 扭秧歌的一只泱</a> <strong>|</strong> <img src="https://yayako-blog.oss-cn-hangzhou.aliyuncs.com/settings/%E5%A4%87%E6%A1%88%E5%9B%BE%E6%A0%87.png" class="lazyload" data-srcset="https://yayako-blog.oss-cn-hangzhou.aliyuncs.com/settings/%E5%A4%87%E6%A1%88%E5%9B%BE%E6%A0%87.png" srcset="" alt="备案图标"> <a target="_blank" rel="noopener" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33032402002017">浙公网安备33032402002017号</a> <strong>|</strong> <a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/#/Integrated/index">浙ICP备20015559号</a></p>

        </div>
      
    
  </footer>


        <a
          id="s-top"
          class="fas fa-arrow-up fa-fw"
          href="javascript:void(0)"
        ></a>
      </div>
    </div>
    <div>
      <script>
window.volantis={};
window.volantis.loadcss=document.getElementById("loadcss");
/********************脚本懒加载函数********************************/
function loadScript(src, cb) {
var HEAD = document.getElementsByTagName('head')[0] || document.documentElement;
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
if (cb) script.onload = cb;
script.setAttribute('src', src);
HEAD.appendChild(script);
}
//https://github.com/filamentgroup/loadCSS
var loadCSS = function( href, before, media, attributes ){
	var doc = window.document;
	var ss = doc.createElement( "link" );
	var ref;
	if( before ){
		ref = before;
	}
	else {
		var refs = ( doc.body || doc.getElementsByTagName( "head" )[ 0 ] ).childNodes;
		ref = refs[ refs.length - 1];
	}
	var sheets = doc.styleSheets;
	if( attributes ){
		for( var attributeName in attributes ){
			if( attributes.hasOwnProperty( attributeName ) ){
				ss.setAttribute( attributeName, attributes[attributeName] );
			}
		}
	}
	ss.rel = "stylesheet";
	ss.href = href;
	ss.media = "only x";
	function ready( cb ){
		if( doc.body ){
			return cb();
		}
		setTimeout(function(){
			ready( cb );
		});
	}
	ready( function(){
		ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
	});
	var onloadcssdefined = function( cb ){
		var resolvedHref = ss.href;
		var i = sheets.length;
		while( i-- ){
			if( sheets[ i ].href === resolvedHref ){
				return cb();
			}
		}
		setTimeout(function() {
			onloadcssdefined( cb );
		});
	};
	function loadCB(){
		if( ss.addEventListener ){
			ss.removeEventListener( "load", loadCB );
		}
		ss.media = media || "all";
	}
	if( ss.addEventListener ){
		ss.addEventListener( "load", loadCB);
	}
	ss.onloadcssdefined = onloadcssdefined;
	onloadcssdefined( loadCB );
	return ss;
};
</script>
<script>
  
  loadCSS("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14/css/all.min.css", window.volantis.loadcss);
  
  
  
  
</script>
<!-- required -->

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5/dist/jquery.min.js"></script>

<script>
  function pjax_fancybox() {
    $(".md .gallery").find("img").each(function () { //渲染 fancybox
      var element = document.createElement("a"); // a 标签
      $(element).attr("class", "fancybox");
      $(element).attr("pjax-fancybox", "");  // 过滤 pjax
      $(element).attr("href", $(this).attr("src"));
      if ($(this).attr("data-original")) {
        $(element).attr("href", $(this).attr("data-original"));
      }
      $(element).attr("data-fancybox", "images");
      var caption = "";   // 描述信息
      if ($(this).attr('alt')) {  // 判断当前页面是否存在描述信息
        $(element).attr('data-caption', $(this).attr('alt'));
        caption = $(this).attr('alt');
      }
      var div = document.createElement("div");
      $(div).addClass("fancybox");
      $(this).wrap(div); // 最外层套 div ，其实主要作用还是 class 样式
      var span = document.createElement("span");
      $(span).addClass("image-caption");
      $(span).text(caption); // 加描述
      $(this).after(span);  // 再套一层描述
      $(this).wrap(element);  // 最后套 a 标签
    })
    $(".md .gallery").find("img").fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
      closeClick: true,
      helpers: {
        overlay: {closeClick: true}
      },
      buttons: [
        "zoom",
        "close"
      ]
    });
  };
  function SCload_fancybox() {
    if ($(".md .gallery").find("img").length == 0) return;
    loadCSS("https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css", document.getElementById("loadcss"));
    setTimeout(function() {
      loadScript('https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js', pjax_fancybox)
    }, 1);
  };
  $(function () {
    SCload_fancybox();
  });
</script>


<!-- internal -->

  
  
  
    
<script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script>

    <script type="text/javascript">
        var imgs=["https://yayako-blog.oss-cn-hangzhou.aliyuncs.com/cover/hd.jpg"];
        if ('false' == 'true') {
          function shuffle(arr){
            /*From countercurrent-time*/
            var n = arr.length;
            while(n--) {
              var index = Math.floor(Math.random() * n);
              var temp = arr[index];
              arr[index] = arr[n];
              arr[n] = temp;
            }
          }
          shuffle(imgs);
        }
	  function Pjax_backstretch(){
        
          $.backstretch(
            imgs,
          {
            duration: "10000",
            fade: "1500"
          });
        
	  }
	  loadScript("https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js",Pjax_backstretch)
    </script>
  




<script>
  function loadIssuesJS() {
    if ($(".md").find(".issues-api").length == 0) return;
    setTimeout(function() {
	
	  loadScript('/js/issues.js');
	
    }, 1);
  };
  $(function () {
    loadIssuesJS();
  });
</script>



  <script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>
<script>
  // https://www.npmjs.com/package/vanilla-lazyload
  // Set the options globally
  // to make LazyLoad self-initialize
  window.lazyLoadOptions = {
    elements_selector: ".lazyload",
    threshold: 0
  };
  // Listen to the initialization event
  // and get the instance of LazyLoad
  window.addEventListener(
    "LazyLoad::Initialized",
    function (event) {
      window.lazyLoadInstance = event.detail.instance;
    },
    false
  );
  document.addEventListener('DOMContentLoaded', function () {
    lazyLoadInstance.update();
  });
  document.addEventListener('pjax:complete', function () {
    lazyLoadInstance.update();
  });
</script>




  
  
    <script>
      window.FPConfig = {
        delay: 0,
        ignoreKeywords: [],
        maxRPS: 5,
        hoverDelay: 25
      };
    </script>
    <script defer src="https://cdn.jsdelivr.net/gh/gijo-varghese/flying-pages@2.1.2/flying-pages.min.js"></script>
  




  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
    var clipboard = new ClipboardJS('.btn-copy', {
        target: function (trigger) {
            return trigger.nextElementSibling
        }
    });
    function wait(callback, seconds) {
        var timelag = null;
        timelag = window.setTimeout(callback, seconds)
    }
    function pjax_initCopyCode() {
		if($(".highlight .code pre").length+$(".article pre code").length==0)return;
        var copyHtml = '';
        copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
        copyHtml += '<i class="fas fa-copy"></i><span>COPY</span>';
        copyHtml += '</button>';
        $(".highlight .code pre").before(copyHtml);
        $(".article pre code").before(copyHtml);
        clipboard.off('success').on('success', function (e) {
            let $btn = $(e.trigger);
            $btn.addClass('copied');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-check-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPIED';
            wait(function () {
                $icon.removeClass('fa-check-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        });
        clipboard.off('error').on('error', function (e) {
            e.clearSelection();
            let $btn = $(e.trigger);
            $btn.addClass('copy-failed');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-times-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPY FAILED';
            wait(function () {
                $icon.removeClass('fa-times-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        })
    }
    $(function () {
        pjax_initCopyCode()
    });
</script>




   <script src="https://cdn.jsdelivr.net/npm/scrollreveal@4.0.6/dist/scrollreveal.min.js"></script>
<script type="text/javascript">
  function pjax_scrollrebeal() {
    ScrollReveal().reveal('.l_main .reveal', {
      distance: '32px',
      duration: '800',
      interval: '20',
      scale: '1',
      easing: 'ease-out'
    });
  }
  $(function () {
    pjax_scrollrebeal();
  });
</script>






  
  
<script src="https://cdn.jsdelivr.net/npm/valine@1.4/dist/Valine.min.js"></script>


<script>
  function emoji(path, idx, ext) {
    return path + "/" + path + "-" + idx + "." + ext;
  }
  var emojiMaps = {};
  for (var i = 1; i <= 54; i++) {
    emojiMaps['tieba-' + i] = emoji('tieba', i, 'png');
  }
  for (var i = 1; i <= 101; i++) {
    emojiMaps['qq-' + i] = emoji('qq', i, 'gif');
  }
  for (var i = 1; i <= 116; i++) {
    emojiMaps['aru-' + i] = emoji('aru', i, 'gif');
  }
  for (var i = 1; i <= 125; i++) {
    emojiMaps['twemoji-' + i] = emoji('twemoji', i, 'png');
  }
  for (var i = 1; i <= 4; i++) {
    emojiMaps['weibo-' + i] = emoji('weibo', i, 'png');
  }
  function pjax_valine() {
    if(!document.querySelectorAll("#valine_container")[0])return;
    let pagePlaceholder = pdata.commentPlaceholder || "快来评论吧~";
    let path = pdata.commentPath;
    if (path.length == 0) {
      let defaultPath = '';
      path = defaultPath || decodeURI(window.location.pathname);
    }
    var valine = new Valine();
    valine.init(Object.assign({"js":"https://cdn.jsdelivr.net/npm/valine@1.4/dist/Valine.min.js","path":null,"placeholder":"快来评论吧~","appId":"crkoKrezsl4I7UWQjAvOy2N1-gzGzoHsz","appKey":"OUvAeTn1CnCmGFdNYVH00G0S","meta":["nick","mail","link"],"requiredFields":["nick","mail"],"enableQQ":true,"recordIP":false,"avatar":"robohash","pageSize":10,"lang":"zh-cn","highlight":true,"visitor":true,"mathJax":false}, {
      el: '#valine_container',
      path: path,
      placeholder: pagePlaceholder,
      emojiCDN: 'https://cdn.jsdelivr.net/gh/volantis-x/cdn-emoji/valine/',
      emojiMaps: emojiMaps,
    }))
  }
  $(function () {
    pjax_valine();
  });
</script>





  
<script src="/js/app.js"></script>



<!-- optional -->

  <script>
const SearchServiceimagePath="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@master/img/";
const ROOT =  ("/" || "/").endsWith('/') ? ("/" || "/") : ("//" || "/" );

$('.input.u-search-input').one('focus',function(){
	
		loadScript('/js/search/hexo.js',setSearchService);
	
})

function listenSearch(){
  
    customSearch = new HexoSearch({
      imagePath: SearchServiceimagePath
    });
  
}
function setSearchService() {
	listenSearch();
	
		document.addEventListener("pjax:success", listenSearch);
	
}
</script>











  <script defer>

  const LCCounter = {
    app_id: 'u9j57bwJod4EDmXWdxrwuqQT-MdYXbMMI',
    app_key: 'jfHtEKVE24j0IVCGHbvuFClp',
    custom_api_server: '',

    // 查询存储的记录
    getRecord(Counter, url, title) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({url})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {url, title: title, times: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    },

    // 发起自增请求
    increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    },

    // 构建自增请求体
    buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "times": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    },

    // 校验是否为有效的 UV
    validUV() {
      var key = 'LeanCloudUVTimestamp';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    },

    addCount(Counter) {
      var enableIncr = '' === 'true' && window.location.hostname !== 'localhost';
      enableIncr = true;
      var getterArr = [];
      var incrArr = [];
      // 请求 PV 并自增
      var pvCtn = document.querySelector('#lc-sv');
      if (pvCtn || enableIncr) {
        var pvGetter = this.getRecord(Counter, 'https://www.yayako.cn' + '/#lc-sv', 'Visits').then((record) => {
          incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-sv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + 1;
              if (pvCtn) {
                pvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#lc-uv');
      if (uvCtn || enableIncr) {
        var uvGetter = this.getRecord(Counter, 'https://www.yayako.cn' + '/#lc-uv', 'Visitors').then((record) => {
          var vuv = this.validUV();
          vuv && incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-uv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + (vuv ? 1 : 0);
              if (uvCtn) {
                uvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(uvGetter);
      }

      // 请求文章的浏览数，如果是当前页面就自增
      var allPV = document.querySelectorAll('#lc-pv');
      if (allPV.length > 0 || enableIncr) {
        for (i = 0; i < allPV.length; i++) {
          let pv = allPV[i];
          let title = pv.getAttribute('data-title');
          var url = 'https://www.yayako.cn' + pv.getAttribute('data-path');
          if (url) {
            var viewGetter = this.getRecord(Counter, url, title).then((record) => {
              // 是当前页面就自增
              let curPath = window.location.pathname;
              if (curPath.includes('index.html')) {
                curPath = curPath.substring(0, curPath.lastIndexOf('index.html'));
              }
              if (pv.getAttribute('data-path') == curPath) {
                incrArr.push(this.buildIncrement(record.objectId));
              }
              if (pv) {
                var ele = pv.querySelector('#lc-pv #number');
                if (ele) {
                  if (pv.getAttribute('data-path') == curPath) {
                    ele.innerText = (record.times || 0) + 1;
                  } else {
                    ele.innerText = record.times || 0;
                  }
                  pv.style.display = 'inline';
                }
              }
            });
            getterArr.push(viewGetter);
          }
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && this.increment(Counter, incrArr);
        })
      }

    },


    fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': this.app_id,
            'X-LC-Key': this.app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      this.addCount(Counter);
    },

    refreshCounter() {
      var api_server = this.app_id.slice(-9) !== '-MdYXbMMI' ? this.custom_api_server : `https://${ this.app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;
      if (api_server) {
        this.fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + this.app_id)
          .then(resp => resp.json())
          .then(({api_server}) => {
            this.fetchData('https://' + api_server);
          });
      }
    }

  };

  LCCounter.refreshCounter();

  document.addEventListener('pjax:complete', function () {
    LCCounter.refreshCounter();
  });
</script>








<script>
function listennSidebarTOC() {
  const navItems = document.querySelectorAll(".toc li");
  if (!navItems.length) return;
  const sections = [...navItems].map((element) => {
    const link = element.querySelector(".toc-link");
    const target = document.getElementById(
      decodeURI(link.getAttribute("href")).replace("#", "")
    );
    link.addEventListener("click", (event) => {
      event.preventDefault();
      window.scrollTo({
		top: target.offsetTop + 100,
		
		behavior: "smooth"
		
	  });
    });
    return target;
  });

  function activateNavByIndex(target) {
    if (target.classList.contains("active-current")) return;

    document.querySelectorAll(".toc .active").forEach((element) => {
      element.classList.remove("active", "active-current");
    });
    target.classList.add("active", "active-current");
    let parent = target.parentNode;
    while (!parent.matches(".toc")) {
      if (parent.matches("li")) parent.classList.add("active");
      parent = parent.parentNode;
    }
  }

  function findIndex(entries) {
    let index = 0;
    let entry = entries[index];
    if (entry.boundingClientRect.top > 0) {
      index = sections.indexOf(entry.target);
      return index === 0 ? 0 : index - 1;
    }
    for (; index < entries.length; index++) {
      if (entries[index].boundingClientRect.top <= 0) {
        entry = entries[index];
      } else {
        return sections.indexOf(entry.target);
      }
    }
    return sections.indexOf(entry.target);
  }

  function createIntersectionObserver(marginTop) {
    marginTop = Math.floor(marginTop + 10000);
    let intersectionObserver = new IntersectionObserver(
      (entries, observe) => {
        let scrollHeight = document.documentElement.scrollHeight + 100;
        if (scrollHeight > marginTop) {
          observe.disconnect();
          createIntersectionObserver(scrollHeight);
          return;
        }
        let index = findIndex(entries);
        activateNavByIndex(navItems[index]);
      },
      {
        rootMargin: marginTop + "px 0px -100% 0px",
        threshold: 0,
      }
    );
    sections.forEach((element) => {
      element && intersectionObserver.observe(element);
    });
  }
  createIntersectionObserver(document.documentElement.scrollHeight);
}

document.addEventListener("DOMContentLoaded", listennSidebarTOC);
document.addEventListener("pjax:success", listennSidebarTOC);
</script>

<!-- more -->

  


<script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.min.js"></script>


<script>
    var pjax;
    document.addEventListener('DOMContentLoaded', function () {
      pjax = new Pjax({
        elements: 'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([pjax-fancybox])',
        selectors: [
          "title",
          "#l_cover",
          "#pjax-container",
          "#pjax-header-nav-list"
        ],
        cacheBust: false,   // url 地址追加时间戳，用以避免浏览器缓存
        timeout: 5000
      });
    });

    document.addEventListener('pjax:send', function (e) {
      //window.stop(); // 相当于点击了浏览器的停止按钮

      try {
        var currentUrl = window.location.pathname;
        var targetUrl = e.triggerElement.href;
        var banUrl = [""];
        if (banUrl[0] != "") {
          banUrl.forEach(item => {
            if(currentUrl.indexOf(item) != -1 || targetUrl.indexOf(item) != -1) {
              window.location.href = targetUrl;
            }
          });
        }
      } catch (error) {}

      window.subData = null; // 移除标题（用于一二级导航栏切换处）
      if (typeof $.fancybox != "undefined") {
        $.fancybox.close();    // 关闭弹窗
      }
      volantis.$switcher.removeClass('active'); // 关闭移动端激活的搜索框
      volantis.$header.removeClass('z_search-open'); // 关闭移动端激活的搜索框
      volantis.$wrapper.removeClass('sub'); // 跳转页面时关闭二级导航

      // 解绑事件 避免重复监听
      volantis.$topBtn.unbind('click');
      $('.menu a').unbind('click');
      $(window).unbind('resize');
      $(window).unbind('scroll');
      $(document).unbind('scroll');
      $(document).unbind('click');
      $('body').unbind('click');
	  
    });

    document.addEventListener('pjax:complete', function () {
      // 关于百度统计对 SPA 页面的处理：
      // 方案一：百度统计>管理>单页应用设置中，打开开启按钮即可对SPA进行统计。 https://tongji.baidu.com/web/help/article?id=324
      // 方案二：取消注释下列代码。 https://tongji.baidu.com/web/help/article?id=235
       

      // 关于谷歌统计对 SPA 页面的处理：
      // 当应用以动态方式加载内容并更新地址栏中的网址时，也应该更新通过 gtag.js 存储的网页网址。
      // https://developers.google.cn/analytics/devguides/collection/gtagjs/single-page-applications?hl=zh-cn
      


      $('.nav-main').find('.list-v').not('.menu-phone').removeAttr("style",""); // 移除小尾巴的移除
      $('.menu-phone.list-v').removeAttr("style",""); // 移除小尾巴的移除
      $('script[data-pjax], .pjax-reload script').each(function () {
        $(this).parent().append($(this).remove());
      });
      try{
          if (typeof $.fancybox == "undefined") {
            SCload_fancybox();
          } else {
            pjax_fancybox();
          }
        
		  Pjax_backstretch()
        
        
        
          pjax_scrollrebeal();
        
        if (typeof IssuesAPI == "undefined") {
          loadIssuesJS();
        }
        
          pjax_initCopyCode();
        
        
          pjax_valine();
        
        
        
        
        
        
      } catch (e) {
        console.log(e);
      }
	  
    });

    document.addEventListener('pjax:error', function (e) {
	  
      window.location.href = e.triggerElement.href;
    });
</script>
 
    </div>
  </body>
</html>
